<?php
/**
 * Created by jinqiang on 2024/8/8 10:04.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Controllers\Op;


use App\Http\Controllers\Controller;
use App\Http\Repository\WmsRepository;
use App\Http\Services\Op\LendService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\Finder\Finder;

class LendController extends Controller
{
    //全员调拨列表
    public function list(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'page' => 'required',
            'limit' => 'required'
        ]);
        $param = $request->all();
        $res = $lendService->search($param);
        return result($res);
    }

    //我的调拨列表
    public function myList(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'page' => 'required',
            'limit' => 'required'
        ]);
        $param = $request->all();
        $param['adduser'] = auth()->guard("api")->user()->name;
        $res = $lendService->search($param);
        return result($res);
    }

    //取消调拨
    public function cancel(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'allocation_number' => 'required'
        ]);
        $param = $request->all();
        $res = $lendService->cancel($param['allocation_number']);
        return $res['code'] === 0 ? success("申请成功") : error($res['msg'], $res);
    }

    //物流
    public function logistics(LendService $lendService)
    {
        $data = $lendService->logistics();
        return result($data);
    }

    //我的借赠还统计
    public function statistic(LendService $lendService)
    {
        $name = auth()->guard("api")->user()->name;
        $res = $lendService->statistic($name);
        return result($res);
    }

    //调拨详情
    public function detail(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'allocation_number' => 'required',
            'groups' => 'required|in:1,2,3,4'//1赠 2借 3还 4销
        ]);
        $param = $request->all();
        if($param['groups'] == 1){
            $returnList = $lendService->returnList($param['allocation_number'], 1);
            $giveList = $lendService->giveList($param['allocation_number']);
            return result([
                'return_list' => $returnList,
                'give_list' => $giveList,
            ]);
        }
        if($param['groups'] == 2){
            $lendList = $lendService->lendList($param['allocation_number']);
            $returnList = $lendService->returnList($param['allocation_number'], 2);
            $ipurchaseList = $lendService->ipurchaseDetail($param['allocation_number']);
            $giveList = $lendService->giveDetail($param['allocation_number']);
            $saleList = $lendService->saleDetail($param['allocation_number']);
            return result([
                'lend_list' => $lendList,
                'return_list' => $returnList,
                'ipurchase_list' => $ipurchaseList,
                'give_list' => $giveList,
                'sale_list' => $saleList
            ]);
        }
        if($param['groups'] == 3){
            $returnList = $lendService->returnList($param['allocation_number'], 3);
            return result([
                'return_list' => $returnList
            ]);
        }
        if($param['groups'] == 4){
            $lendList = $lendService->lendList($param['allocation_number']);
            $returnList = $lendService->returnList($param['allocation_number'], 2);
            return result([
                'lend_list' => $lendList,
                'return_list' => $returnList
            ]);
        }
        return result();
    }

    //归还所选
    public function returnOnly(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'is_subject' => 'required'
        ]);
        $param = $request->all();
        $res = $lendService->returnOnly($param);
        return $res['code'] === 0 ? success("已提交归还任务") : error($res['msg'], $res);
    }

    //归还所选--系统处理
    public function returnSys(Request $request, LendService $lendService)
    {
        $param = $request->all();
        $res = $lendService->returnSys($param);
        return $res['code'] === 0 ? success("系统已归还") : error($res['msg'], $res);
    }

    //赠送转归还
    public function returnGive(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'is_subject' => 'required'
        ]);
        $param = $request->all();
        $res = $lendService->returnGive($param);
        return $res['code'] === 0 ? success("已提交归还任务") : error($res['msg'], $res);
    }

    //借出转赠送
    public function giveLend(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'is_subject' => 'required'
        ]);
        $param = $request->all();
        $res = $lendService->giveLend($param);
        return $res['code'] === 0 ? success("已提交赠送任务") : error($res['msg'], $res);
    }

    //借出转赠送--系统处理
    public function giveLendSys(Request $request, LendService $lendService)
    {
        $param = $request->all();
        $res = $lendService->giveLendSys($param);
        return $res['code'] === 0 ? success("已提交赠送任务") : error($res['msg'], $res);
    }

    //借出转内购
    public function ipurchase(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'allocation_number' => 'required',
            'detail' => 'required',
            'discount' => 'required',
            'is_subject' => 'required',
            'img' => 'required'
        ]);
        $param = $request->all();
        $res = $lendService->ipurchase($param);
        return $res['code'] === 0 ? success("已提交内购任务") : error($res['msg'], $res);
    }

    //创建调拨计划---借出、赠送、销售
    public function createPlan(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'groups' => 'required|in:1,2,4',
            'detail' => 'required',
        ]);
        $param = $request->all();
        $res = $lendService->createPlan($param);
        return $res['code'] === 0 ? success("创建调拨计划成功，请勾选待发审批列表，并发起审批") : error($res['msg'], $res);
    }

    //发起审批---借出、赠送、销售
    public function approval(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'groups' => 'required|in:1,2,4',
            'allocation_number' => 'required',
        ]);
        $param = $request->all();
        $res = $lendService->approval($param);
        return $res['code'] === 0 ? success("审批发起成功, 请前往飞书查看当前审批状态, 耐心等待...") : error($res['msg'], $res);
    }

    //关闭调拨计划---借出、赠送
    public function close(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'allocation_number' => 'required',
            'remark' => 'required'
        ]);
        $param = $request->all();
        $res = $lendService->close($param['allocation_number'], $param['remark']);
        return $res['code'] === 0 ? success("成功关闭调拨计划") : error($res['msg'], $res);
    }

    //预留解除
    public function free(Request $request)
    {
        $this->validate($request, [
            'adduser' => 'required',
            'list' => 'required'
        ]);
        $param = $request->all();
        $user = auth()->guard("api")->user();
        if(!in_array($user->name, ["金强", "董鹏勃"])){
            return ['code' => -1, 'msg' => '当前无操作权限, 403'];
        }
        $list = $param['list'];
        if(empty($list)){
            return error("请输入sku");
        }
        foreach($list as $item){
            $num = (Int)$item['num'];
            $skuCode = $item['sku_code'];
            if(empty($skuCode)){
                return error("sku不能为空");
            }
            if($num <= 0){
                return error("请输入申请数量");
            }
        }
        $addUser = $param['adduser'];
        foreach ($list as $item){
            $num = (Int)$item['num'];
            $skuCode = $item['sku_code'];
            $freeKey = "ALLOCATION_LEND_{$addUser}_{$skuCode}";
            Cache::put($freeKey, $num, Carbon::now()->addMinutes(5));//缓存有效期5分钟
        }
        return success();
    }

    //调拨转交
    public function handover(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'fromUser' => 'required',
            'toUser' => 'required',
            'is_ok' => 'required|in:0,1'
        ]);
        $param = $request->all();
        $user = auth()->guard("api")->user();
        if(!in_array($user->name, ["金强"])){
            return ['code' => -1, 'msg' => '当前无操作权限, 403'];
        }
        $res = $lendService->handover($param);
        return $res['code'] === 0 ? success("操作成功", $res['data']) : error($res['msg'], $res);
    }

    //审批进度
    public function approvalProcess(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'id' => 'required',
            'run_id' => 'required',
        ]);
        $param = $request->all();
        $res = $lendService->approvalProcess($param);
        return result($res);
    }

    //调拨推送
    public function push(Request $request, LendService $lendService)
    {
        $this->validate($request, [
            'allocation_number' => 'required',
            'is_subject' => 'required'
        ]);
        $param = $request->all();
        $user = auth()->guard("api")->user();
        if(!in_array($user->name, ["金强", "董鹏勃"])){
            return ['code' => -1, 'msg' => '当前无操作权限, 403'];
        }
        $res = WmsRepository::pushAllocation($param['allocation_number'], $param['is_subject']);
        return $res['code'] === 0 ? success("操作成功") : error($res['msg'], $res);
    }

    //获取导出文件列表
    public function excelList()
    {
        $user = auth()->guard("api")->user();
        $name = $user->name;
        $nameId = $user->id;
        $processKey = "LEND_EXCEL_EXPORT_{$nameId}";
        //获取正在导出的任务进度
        $cache = Cache::get($processKey) ?: [];
        $finder = new Finder();
        $files = $finder->files()->in(storage_path("cache/allocation"))->name("全员借赠还_{$name}_*.xls");
        $data = [];
        $createTimeList = [];
        foreach ($files as $file) {
            $fileName = $file->getFilename();
            $createTime = preg_match("/全员借赠还_(.*?)_(\d{14})\.xls/is", $fileName, $d) ? $d[2] : "";
            $data[] = [
                'create_user' => $name,
                'create_time' => date('Y-m-d H:i:s', strtotime($createTime)),
                'name' => $fileName,
                'status' => ($cache['file']??"") == $fileName ? 0 : 1,
                'process' => ($cache['file']??"") == $fileName ? $cache['process'] : 100
            ];
            $createTimeList[] = strtotime($createTime);
        }
        array_multisort($createTimeList, SORT_DESC, $data);
        return result(['data' => $data, 'cache' => $cache]);
    }

    //获取导出进度
    public function exportCache()
    {
        $user = auth()->guard("api")->user();
        $nameId = $user->id;
        $processKey = "LEND_EXCEL_EXPORT_{$nameId}";
        //获取正在导出的任务进度
        $cache = Cache::get($processKey) ?: [];
        return result($cache);
    }

    //导出执行
    public function exportData(Request $request)
    {
        $param = $request->all();
        $user = auth()->guard("api")->user();
        $name = $user->name;
        $nameId = $user->id;
        //添加导出的任务进度
        $processKey = "LEND_EXCEL_EXPORT_{$nameId}";
        if(Cache::get($processKey)){
            return error("添加失败, 最近一次导出计划还未完成");
        }
        $cTime = date('YmdHis');
        $filename = "全员借赠还_{$name}_{$cTime}.xls";
        $file = storage_path("cache/allocation/").$filename;
        $spreadsheet = new Spreadsheet();
        $writer = new Xlsx($spreadsheet);
        $writer->save($file);
        if(file_exists($file)){
            $cache = ['file' => $filename, 'process' => 0, 'param' => $param];
            Cache::put($processKey, $cache, Carbon::now()->addSeconds(60));
            $cmd = 'php '.base_path().'/artisan command:exportData --type=lend --id='.$nameId.' >/dev/null 2>&1 &';
            ppopen($cmd);
            return success("添加成功", $cache);
        }else{
            return error("添加失败, 创建文件失败");
        }
    }
}
